import _ from "lodash";
import moment from "moment";

/**
 * 修复缩放问题
 * @returns {number}
 */
const detectZoom = () => {
  let ratio = 0,
    screen = window.screen,
    ua = navigator.userAgent.toLowerCase();

  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio;
  } else if (~ua.indexOf("msie")) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth;
  }

  if (ratio) {
    ratio = Math.round(ratio * 100);
  }

  return ratio;
};
// eslint-disable-next-line no-unused-vars
const fixZoom = () => {
  let zoom = detectZoom();
  if (zoom < 100) {
    document.body.style.zoom = 100 / zoom;
  } else {
    document.body.style.zoom = 1;
  }
};
// window.addEventListener("resize", fixZoom);
// setTimeout(fixZoom, 200);
/**
 *
 * @param computemark 验证通过的计算符号 eg: 大于两个月 computemark:> addTimeVal:2 验证通过
 * @param addTimeVal
 * @param message
 * @param key years/months/days 参考http://momentjs.cn/docs/#/manipulating/add/
 */
const compute = (computemark, addTimeVal, message, value, key) => {
  let pass = true;
  if (value && value.length) {
    const beginTimeAddDay = moment(value[0]).add(addTimeVal, key);
    let endTime = moment(value[1]);
    let resultTime = endTime - beginTimeAddDay;
    switch (computemark) {
      case ">":
        pass = resultTime > 0;
        break;
      case ">=":
        pass = resultTime >= 0;
        break;
      case "=":
      case "==":
      case "===":
        pass = resultTime === 0;
        break;
      case "<=":
        pass = resultTime >= 0;
        break;
      case "<":
        pass = resultTime < 0;
        break;
      default:
        console.error("请打码给出计算单位");
        break;
    }
  }
  return pass;
};

export default {
  // 查询当前月的 起止日期
  getCurrentMonthStartEndTimes() {
    //获取本月
    const startDate = moment(
      moment()
        .month(moment().month())
        .startOf("month")
        .valueOf()
    ).format("YYYY-MM-DD");
    const endDate = moment(
      moment()
        .month(moment().month())
        .endOf("month")
        .valueOf()
    ).format("YYYY-MM-DD");
    return [startDate, endDate];
  },
  // 获取当前月分
  getCurMonth: () => {
    return (
      moment()
        .toDate()
        .getMonth() + 1
    ).toString();
  },
  // 获取当前月的天数
  getDaysInCurMonth: () => {
    return moment().daysInMonth();
  },
  // 获取延后几个月的某个月内的天数，默认为下个月的天数
  getDaysInNextMonth: (nextValue = 1) => {
    return moment()
      .add({ months: nextValue })
      .daysInMonth();
  },
  // 获取提前几个月的某个月内的天数，默认为上个月的天数
  getDaysInPreMonth: (preValue = 1) => {
    return moment()
      .subtract({ months: preValue })
      .daysInMonth();
  },
  // 这个... 等于上面三个接口的综合体
  getDaysInMonth: (param = {}) => {
    if (param && Object.keys(param).length > 0) {
      let { next, pre } = param;
      if (next) {
        return moment()
          .add({ months: next })
          .daysInMonth();
      } else {
        return moment()
          .subtract({ months: pre })
          .daysInMonth();
      }
    }
    return moment().daysInMonth();
  },
  time: {
    // 获取当前季度区间
    /**
     ["2020-01-01", "2020-03-31"]
     ["2020-04-01", "2020-06-30"]
     ["2020-07-01", "2020-09-30"]
     ["2019-10-01", "2019-12-31"]
     * @returns {Array}
     */
    getCurrQuarter: () => {
      let date = [];
      let start = moment()
        .startOf("quarter")
        .format("YYYY-MM-DD");
      let end = moment()
        .endOf("quarter")
        .format("YYYY-MM-DD");
      date.push(start);
      date.push(end);
      return date;
    },
    getCurrYaer: () => {
      return moment().format("YYYY") + "";
    },
    // 获取 年前 年中 年后 下拉列表数据
    getDropYears() {
      let years = [];
      let year = moment().format("YYYY");
      years.push(Number(year) - 1 + "");
      years.push(year);
      years.push(Number(year) + 1 + "");
      return years.map(res => {
        return { code: res, label: res };
      });
    }
  },
  /**
   *通过键名获取对象中的值
   * @param obj 目标数组
   * @param deepKey 深度key的名称 eg：要查目标数组中的aa.bb.cc的值 传入aa.bb.cc
   * @returns {*}
   */
  getDeepValue: (obj = {}, deepKey) => {
    const _deepKey = deepKey.split(".");
    let object = _.cloneDeep(obj);
    let keyObj = val => {
      object = object[val];
      return keyObj;
    };
    _deepKey.forEach(key => {
      keyObj(key);
    });
    return object;
  },
  /**
   *
   * @param dom 目标区域,若无则全部打印
   * @returns null
   */
  print(dom) {
    let printRange = document.getElementById("print-range");
    let target;
    if (dom) {
      if (!printRange) {
        printRange = document.createElement("DIV");
        printRange.setAttribute("id", "print-range");
        printRange.setAttribute("class", "printRange");
        if (_.isArray(dom)) {
          _.forEach(dom, d => {
            printRange.innerHTML =
              printRange.innerHTML +
              d.outerHTML +
              "<div style='height: 16px'/>";
          });
          target = dom[dom.length - 1];
        } else {
          printRange.innerHTML = dom.outerHTML;
          target = dom;
        }
        target.appendChild(printRange);
      }
    }
    window.print();
    if (target) {
      target.removeChild(printRange);
    }
  },

  //产生随机数函数
  uuid() {
    return (
      new Date().getTime() * 1000 + (Math.floor(Math.random() * 10) % 1000)
    );
  },
  // 通过Code获取value，适用code-label对应list
  getLabelByCode(codeLabelList = [], code) {
    try {
      return codeLabelList.find(item => item.code == code).label;
    } catch (e) {
      console.error("未找到编号对应名称。");
      return "";
    }
  },
  validatePass: {
    // 验证月份区间的日历时间
    monthInterval(computemark, months, message) {
      return (rule, value, callback) => {
        const pass = compute(computemark, months, message, value, "months");
        pass ? callback() : callback(new Error(message));
      };
    },
    // 验证天数区间的日历时间
    dayInterval(computemark, days, message) {
      return (rule, value, callback) => {
        const pass = compute(computemark, days, message, value, "days");
        pass ? callback() : callback(new Error(message));
      };
    },
    // 验证年份区间的日历时间
    yearInterval(computemark, years, message) {
      return (rule, value, callback) => {
        const pass = compute(computemark, years, message, value, "years");
        pass ? callback() : callback(new Error(message));
      };
    }
  },
  // 全屏窗口
  screen: {
    // 全屏
    fullScreen({ element, curFullscreen }) {
      if (curFullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen();
        }
      }
      return !curFullscreen;
    }
  },
  // 全屏加载中
  store: {
    showLoading: () => {
      const Store = window.Store;
      if (Store) {
        Store.state.MainStore.count == 0 &&
          Store.commit("MainStore/showLoading");
        Store.commit("MainStore/addCount");
        // 一分钟后 如果还在加载，关闭加载框，针对服务器异常情况
        setTimeout(() => {
          Store.state.MainStore.loading &&
            Store.commit("MainStore/hideLoading");
          Store.commit("MainStore/clearCount");
        }, 60000);
      }
    },
    hideLoading: () => {
      const Store = window.Store;
      if (Store) {
        setTimeout(() => {
          Store.commit("MainStore/reduceCount");
          Store.state.MainStore.count == 0 &&
            Store.commit("MainStore/hideLoading");
        }, 200);
      }
    }
  },
  fixEdgeSelect(isVisible) {
    const isEdge = window.navigator.userAgent.includes("Edge");
    if (isEdge && !isVisible) {
      document
        .querySelectorAll("body > .el-select-dropdown.el-popper")
        .forEach(it => it.remove());
    }
  }
};
